<?php
abstract class Generic_Record {
    protected static $table; //instance of MysqlTable
    private $row;

    public static function initialize($db, $tablename, $translate ) {
        assert('!isset(static::$table); /* Already initialized! */');
        $table = new MysqlTable($db,$tablename);
        foreach ($translate as $field=>$fcn) $table->set_translate($field,$fcn);
        static::$table = $table;
    }
    
    public function __construct ($row) {
        assert('$row instanceof MysqlRow');
        $this->row = $row;
    }
    
    public static function load_by_id($id) {
        $class = get_called_class();
        $table = static::$table;
        $row = $table->fetch_row_by_id($id);
        return $row ? new $class($row) : $row;
    }
    
    public static function load_multiple($where) {
        $class = get_called_class();
        $table = static::$table;
        $rows = array();
        foreach ($table->fetch_rows($where) as $row) 
            $rows[] = new $class($row);
        return $rows;
    }
    
    public static function load_by_field($field,$val) {
        $class = get_called_class();
        $table = static::$table;
        $row = $table->fetch_row_by_field($field,$val);
        return $row ? new $class($row) : $row;
    }
    
    public static function create($values) {
        $class = get_called_class();
        $table = static::$table;
        $row = $table->new_row($values);
        return new $class($row);
    }
    
    public static function delete_by_id($id) {
        $table = static::$table;
        $table->delete_row_by_id($id);
    }
    
    // Returns True if we modified anything.
    protected function update($values) {
        $row = $this->row;
        $row->set_array($values);
    }
    
    public function save() { $this->row->save(); }
    
    public function is_modified() { return $this->row->is_modified(); }
    
    public function get($field) { return $this->row->get($field); }
    
    public function set($field,$val) { $this->row->set($field,$val); }
    
    public function get_json() {
        return $this->row->get_json();
    }
    
    public static function escape($val) {
        $table = static::$table;
        return $table->db_link->escape_string($val);
    }
    
}
?>